﻿using System;
using System.Collections.Generic;
using System.Text;
using RAP.Framework.Libary.Utils;
using RAP.Framework.Libary.DomTemplateBuilder.Element.Collection.TimeIterate;
using RAP.Framework.Libary.DomTemplateBuilder.Interface;

namespace RAP.Framework.Libary.DomTemplateBuilder.Handler.TimeIterate
{
	/// <summary>
	/// 日期迭代器的Handler
	/// </summary>
	public class DateIterateHandler : TimeIterateBaseHandler
	{
		public new DateIterate Element
		{
			get
			{
				return base.Element as DateIterate;
			}
		}

		protected IDictionary<TimeStyles, TimeIterateBaseHandler> dateHandlersCache = new Dictionary<TimeStyles, TimeIterateBaseHandler> ( );
		protected TimeIterateBaseHandler GetHandler ( TimeStyles timeStyle )
		{
			if ( dateHandlersCache.ContainsKey ( timeStyle ) )
			{
				return dateHandlersCache[ timeStyle ];
			}
			var handlerType = DomTemplateManager.GetHandlerType ( "Iterate.{0}".format ( timeStyle.GetNames ( "None" ) ) );
			if ( handlerType == null )
			{
				throw new NullReferenceException ( "获取指定日期类型：{0}的Handler失败，类型不存在！".format ( timeStyle.GetNames ( ) ) );
			}
			var handler = handlerType.Assembly.CreateInstance ( handlerType.FullName ) as TimeIterateBaseHandler;
			if ( handler == null )
			{
				throw new NullReferenceException ( "实例化指定日期类型：{0}的Handler对象错误！".format ( timeStyle.GetNames ( ) ) );
			}
			handler.Element = this.Element as TimeIterateBase;
			dateHandlersCache[ timeStyle ] = handler;
			return handler;
		}

		public override void DoRender ( StringBuilder writer, object rootParamObject, object parentParamObject, ITemplateRenderContext context )
		{
			var property = this.GetPropertyName ( this.Element.TimeStyle, rootParamObject, parentParamObject, context );
			var timeStyleValue = this.GetPropertyValue
			(
				property
				, rootParamObject
				, parentParamObject
				, context
			).IsNullOrEmptyValue ( string.Empty );
			var handler = this.GetHandler ( timeStyleValue.ToEnumValue<TimeStyles> ( ) );
			handler.DoRender ( writer, rootParamObject, parentParamObject, context );
		}

		public override void Dispose ( )
		{
			foreach ( var handler in this.dateHandlersCache.Values )
			{
				handler.Dispose ( );
			}
			this.dateHandlersCache.Clear ( );
			base.Dispose ( );
		}
	}
}
